﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;

namespace QuickResizer
{
	public static class ImageHelper
	{
		/// <summary>
		/// Resizes the passed in image file based on the passed in resizer
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="resizer"></param>
		public static void Resize(string filePath, ResizerItem resizer)
		{
			FileInfo fileInfo = new FileInfo(filePath);
			if (fileInfo.Exists)
			{
				string destinationPath = CheckDestination(fileInfo, resizer.SubFolder);
				string filename = fileInfo.Name.Substring(0, fileInfo.Name.Length - fileInfo.Extension.Length);

				// retrieve the source image
				Image imageOriginal = Image.FromFile(fileInfo.FullName);
				// resize the image
				Image newImage = ResizeImage(imageOriginal, resizer.Width, resizer.Height);
				// build the new file name and path
				string destinationFile = destinationPath + @"\" + resizer.Prefix + filename + resizer.Suffix + fileInfo.Extension;
				// save the new image
				newImage.Save(destinationFile);
				newImage.Dispose();
			}
		}

		/// <summary>
		/// Verifies that the destination directory exists.  If it does not, it is created
		/// </summary>
		private static string CheckDestination(FileInfo fileInfo, string subFolder)
		{
			string testPath;

			testPath = fileInfo.DirectoryName;
			if (!string.IsNullOrWhiteSpace(subFolder))
				testPath += @"\" + subFolder;
			if (!Directory.Exists(testPath))
				Directory.CreateDirectory(testPath);
			return testPath;
		}

		/// <summary>
		/// Resizes the original image
		/// </summary>
		/// <param name="image"></param>
		/// <param name="maxWidth"></param>
		/// <param name="maxHeight"></param>
		/// <returns></returns>
		private static Bitmap ResizeImage(Image image, int maxWidth, int maxHeight)
		{
			Bitmap originalImage = new Bitmap(image);
			int newWidth = originalImage.Width;
			int newHeight = originalImage.Height;
			double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;

			if (aspectRatio <= 1 && originalImage.Width > maxWidth)
			{
				newWidth = maxWidth;
				newHeight = (int)Math.Round(newWidth / aspectRatio);
			}
			else if (aspectRatio > 1 && originalImage.Height > maxHeight)
			{
				newHeight = maxHeight;
				newWidth = (int)Math.Round(newHeight * aspectRatio);
			}

			Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);

			Graphics g = Graphics.FromImage(newImage);
			g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
			g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

			originalImage.Dispose();

			return newImage;
		}

	}
}
